/**
 * Copyright (C), 2001-2031, www.bosssof.com.cn
 * FileName: LoginServiceImpl.java
 * Author: shixianwei
 * Date: 2024/8/13 21:47
 * Description:
 * <p>
 * History:
 * Date          Author   Version  Desc
 * 2024-01-01    bosssoft  1.0.0   initialize this file
 */
package com.bosssoft.setp.service.impl;


import com.bosssoft.setp.exception.BusinessException;
import com.bosssoft.setp.model.business.shop.TrainingPlace;
import com.bosssoft.setp.pojo.dto.LoginDTO;
import com.bosssoft.setp.pojo.vo.DeviceInformation;
import com.bosssoft.setp.pojo.vo.LoginVO;
import com.bosssoft.setp.pojo.vo.UserRole;
import com.bosssoft.setp.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import xyz.erupt.core.exception.EruptApiErrorTip;
import xyz.erupt.jpa.dao.EruptDao;
import xyz.erupt.upms.model.EruptUser;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @className: LoginServiceImpl
 * @description: 登录业务的实现类
 * @author: shixianwei
 * @date: 2024/8/13 21:47
 * @since 1.0
 **/
@Slf4j
@Validated
@Service
public class LoginServiceImpl implements LoginService {

    /**
     * 门店ID
     */
    private static final String PROPERTY_NAME = "userId";
    /**
     * 手机号
     */
    private static final String PROPERTY_PHONE_NUMBER = "phoneNumber";
    /**
     * 设备信息
     */
    private static final String PROPERTY_DEVICE_INFORMATION = "deviceInformation";

    @Autowired
    private EruptDao eruptDao;

    @Override
    public LoginVO logWithIdAndPassword(LoginDTO loginDTO) {
        // 获取门店ID
        LoginVO loginVO = new LoginVO();
        if (loginDTO.getUserId() != null && loginDTO.getPhoneNumber() != null
                && loginDTO.getPassword() != null && loginDTO.getDeviceInformation() != null) {
            EruptUser eruptUser = eruptDao.lambdaQuery(EruptUser.class)
                    .eq(EruptUser::getPhone, loginDTO.getPhoneNumber())
                    .one();
            if (eruptUser != null) {
                if (eruptUser.getPassword().equals(loginDTO.getPassword())) {
                    if (eruptUser.getStatus()) {
                        String sql = "SELECT id FROM setp_training_place WHERE number = ? ";
                        try {
                            eruptDao.getJdbcTemplate().queryForObject(
                                    sql, Long.class, loginDTO.getUserId());
                        }  catch (Exception e) {
                            log.error("该门店ID不存在", e);
                            throw new BusinessException("该门店ID不存在");
                        }
                            Long matchId = eruptDao.getJdbcTemplate().queryForObject(
                                    sql, Long.class, loginDTO.getUserId());
                            String sql1 = "SELECT id FROM setp_shop_member WHERE training_place_id = ?";
                            try {
                                eruptDao.getJdbcTemplate().queryForObject(
                                        sql1, Long.class, matchId);
                            }catch (Exception e) {
                                log.error("该门店下没有人员", e);
                                throw new BusinessException("该门店下没有人员");
                            }
                                Long id1 = eruptDao.getJdbcTemplate().queryForObject(
                                        sql1, Long.class, matchId);
                                String sql2 = "SELECT  user_id FROM setp_shop_link_user WHERE relationship_id = ? ";
                                try {
                                    eruptDao.getJdbcTemplate().queryForList(
                                            sql2, Long.class, id1);
                                }catch (Exception e) {
                                    log.error("该人员不在此门店下面!", e);
                                    throw new BusinessException("该人员不在此门店下面！");
                                }
                                List<Long> id2 = eruptDao.getJdbcTemplate().queryForList(
                                        sql2, Long.class, id1);
                                Long memberId = eruptUser.getId();
                                for(int m1 = 0; m1 < id2.size(); m1++){
                                    if (memberId.equals(id2.get(m1))) {

                                        String sql3 = "SELECT status FROM setp_device WHERE mobile_tel = ? AND device_no = ?";
                                        try {
                                            eruptDao.getJdbcTemplate().queryForObject(
                                                    sql3, String.class, loginDTO.getPhoneNumber(), loginDTO.getDeviceInformationDeviceNo());
                                        }catch (Exception e) {
                                            log.error("无法使用该设备登录账号", e);
                                            throw new BusinessException("无法使用该设备登录账号");
                                        }
                                        String status1 = eruptDao.getJdbcTemplate().queryForObject(
                                                sql3, String.class, loginDTO.getPhoneNumber(), loginDTO.getDeviceInformationDeviceNo());
                                        if ("审核通过".equals(status1)) {
                                            loginVO.setUserId(loginDTO.getUserId());
                                            loginVO.setPhoneNumber(loginDTO.getPhoneNumber());
                                            loginVO.setDeviceInformation(loginDTO.getDeviceInformation());
                                            /**
                                             * 获取角色列表
                                             */
                                            String sql4 = "SELECT role_id FROM e_upms_user_role WHERE user_id = ?";
                                            List<Long> roles = eruptDao.getJdbcTemplate().queryForList(
                                                    sql4, Long.class, eruptUser.getId());
                                            List<UserRole> userRoles = new ArrayList<>();
                                            for(int i = 0; i < roles.size(); i++) {
                                                UserRole userRole = new UserRole();
                                                String sql5 = "SELECT name FROM e_upms_role WHERE id = ?";
                                                userRole.setUserType(eruptDao.getJdbcTemplate().queryForObject(
                                                        sql5, String.class, roles.get(i)));
                                                String sql6 = "SELECT menu_id FROM e_upms_role_menu WHERE role_id = ?";
                                                List<Long> powers = eruptDao.getJdbcTemplate().queryForList(
                                                        sql6, Long.class, roles.get(i));
                                                List<String> authorizationInformation1 = new ArrayList<>();
                                                for(int j = 0; j < powers.size(); j++) {
                                                    String sql7 = "SELECT name FROM e_upms_menu WHERE id = ?";
                                                    String power1 =eruptDao.getJdbcTemplate().queryForObject(
                                                            sql7, String.class, powers.get(j));
                                                    authorizationInformation1.add(power1);
                                                }
                                                userRole.setAuthorizationInformation(authorizationInformation1);
                                                userRoles.add(userRole);
                                            }
                                            loginVO.setRole(userRoles);
                                            return loginVO;
                                        } else {
                                            throw new BusinessException("无法使用该设备登录账号");
                                        }
                                    }
                                }
                                throw new BusinessException("该人员不在此门店下面！");
                    } else {
                        throw new BusinessException("该用户处于禁用状态！");
                    }
                } else {
                    throw new BusinessException("密码错误");
                }
            } else {
                throw new BusinessException("该用户不存在！");
            }
        }
        throw new BusinessException("门店ID和手机号，以及密码设备不能为空！");


    }
}

